import {AfterViewInit, Component, ViewChild} from '@angular/core';
import {GnJsonTableComponent} from 'geminis-ng';
import {NzTreeNode} from 'ng-zorro-antd/tree';
import {CategoryTreeComponent} from "../category-tree/category-list.component";

@Component({
  selector: 'everydata-category-list',
  template: `
    <everydata-category-tree [showRoot]="true" (treeInitialed)="loadData($event)" (treeClick)="loadData($event)">
      <gn-json-table url="/everydata-pc/assets/forms/category/table.json"
                     (configLoaded)="loadData(tree.nzTree.getSelectedNodeList())"></gn-json-table>
    </everydata-category-tree>
  `
})
export class CategoryListComponent implements AfterViewInit {

  @ViewChild(GnJsonTableComponent, {static: true}) table!: GnJsonTableComponent;
  @ViewChild(CategoryTreeComponent, {static: true}) tree!: CategoryTreeComponent;

  loadData(nodes: NzTreeNode[]): void {
    if (nodes.length === 0 || !this.table.config) {
      return;
    }
    const node = nodes[0];
    this.table.config.buttons!.newForm!.params!.defaultValue.parentId = node.key;
    this.table.config.buttons!.newForm!.params!.defaultValue.parentPath = node.origin.data.pathId;
    this.table.config.filterGroup.filters[0].value = node.key;
    this.table.config.filterGroup.filters[0].compareType = (node.key === null || node.key === '') ? 'is null' : '=';

    this.table.table.loadDataAndCleanSelection();
  }

  ngAfterViewInit(): void {
    this.table.table.dataDeleted.subscribe(() => {
      this.tree.tree.reloadSelectNode();
    });
    this.table.button.newButton.ok.subscribe(() => {
      this.tree.tree.reloadSelectNode();
    });
    this.table.button.editButton.ok.subscribe(() => {
      this.tree.tree.reloadSelectNode();
    });
  }

}

